import socket
import threading
import pyaudio


class Client:
    def __init__(self):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.target_ip = '192.168.192.109'
        self.target_port = 9809
        print(self.target_port, type(self.target_port))
        self.chunk_size = 1024  # 512
        self.audio_format = pyaudio.paInt16
        self.channels = 1
        self.rate = 20000

        self.p = pyaudio.PyAudio()
        self.playing_stream = self.p.open(format=self.audio_format, channels=self.channels, rate=self.rate, output=True,
                                          frames_per_buffer=self.chunk_size)
        self.recording_stream = self.p.open(format=self.audio_format, channels=self.channels, rate=self.rate,
                                            input=True,
                                            frames_per_buffer=self.chunk_size)

        self.running = False

        print("Client created")

    def connect_to_server(self):
        try:
            self.s.connect((self.target_ip, self.target_port))
            self.running = True
            print("Connected to server")
            self.start_communication()
        except Exception as e:
            print("Couldn't connect to server:", e)

    def start_communication(self):
        receive_thread = threading.Thread(target=self.receive_server_data)
        send_thread = threading.Thread(target=self.send_data_to_server)

        receive_thread.start()
        send_thread.start()

        # 等待线程结束
        receive_thread.join()
        send_thread.join()

    def receive_server_data(self):
        while self.running:
            try:
                data = self.s.recv(1024)
                self.playing_stream.write(data)
            except:
                pass

    def send_data_to_server(self):
        while self.running:
            try:
                data = self.recording_stream.read(1024)
                self.s.sendall(data)
            except:
                pass

    def stop(self):
        self.running = False

        # 关闭连接
        self.s.close()

        # 停止音频流
        self.playing_stream.stop_stream()
        self.playing_stream.close()
        self.recording_stream.stop_stream()
        self.recording_stream.close()
        self.p.terminate()
